package com.lxw.station.controller;

import com.lxw.station.core.R;
import com.lxw.station.core.Result;
import com.lxw.station.entity.Article;
import com.lxw.station.service.ArticleService;
import com.lxw.station.api.CSDNApi;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/article")
public class ArticleController {

    @Resource
    ArticleService articleService;

    /**
     * 新增
     * @return
     */
    @RequestMapping("/save")
    public Result<Object> save() {
        List<Article> articles = CSDNApi.getArticles();
        List<Article> list = articleService.list();
        List<Article> article4insert = new ArrayList<>();
        List<Article> article4update = new ArrayList<>();
        if (CollectionUtils.isEmpty(list)) {
            article4insert = articles;
        } else {
            Map<String, Article> dbArticleMap = list.stream().collect(Collectors.toMap(Article::getArticleId, Function.identity()));
            for (Article article : articles) {
                Article articleFromDb = dbArticleMap.get(article.getArticleId());
                if (articleFromDb == null) {
                    article4insert.add(article);
                } else {
                    articleFromDb.setCollectCount(article.getCollectCount());
                    articleFromDb.setViewCount(article.getViewCount());
                    articleFromDb.setFormatTime(article.getFormatTime());
                    article4update.add(articleFromDb);
                }
            }
        }
        if (!CollectionUtils.isEmpty(article4insert)) {
            articleService.saveBatch(article4insert);
        }
        if (!CollectionUtils.isEmpty(article4update)) {
            articleService.updateBatchById(article4update);
        }
        return R.ok();
    }

}
